#include "runner_common.h"
#include "utils.h"
#include <string.h>

void run_strc_init(prun_strc data)
{
    data->argc = data->__alloc_cnt = 0;
    data->argv = NULL;
}

void run_strc_free(prun_strc data)
{
    if (!data->argc || data->argv == NULL)
        return;
    for (int i = 0; i < data->argc; i++)
        if (data->argv[i] != NULL)
            free(data->argv[i]);
    free(data->argv);
}

void run_strc_add(prun_strc data, char *expr)
{
    data->argc++;
    if ((data->argc + 1) > data->__alloc_cnt)
    {
        data->__alloc_cnt = (data->argv != NULL) ? data->__alloc_cnt << 1 : 2;
        data->argv = (char **)xrealloc(data->argv, data->__alloc_cnt * sizeof(char *));
    }
    data->argv[data->argc - 1] = strdup(expr);
    data->argv[data->argc] = NULL;
}

run_strc run_strc_copy(prun_strc data)
{
    run_strc res; run_strc_init(&res);
    res.argc = data->argc;
    res.__alloc_cnt = data->argc + 1;
    res.argv = (char **)xmalloc(sizeof(char *) * (data->argc + 1));
    for (int i = 0; i < data->argc; i++)
        if (data->argv[i] != NULL)
            res.argv[i] = strdup(data->argv[i]);
        else
            res.argv[i] = NULL;

    res.argv[res.argc] = NULL;
    return res;
}


int8_t is_cd_case(prun_strc data)
{
    if (data->argc && data->argv != NULL && data->argv[0] != NULL)
        return strncmp(data->argv[0], "cd", 2 * sizeof(char)) == 0;
    else
        return 0;
}


int8_t is_exit_case(prun_strc data)
{
    if (data->argc && data->argv != NULL && data->argv[0] != NULL)
        return strncmp(data->argv[0], "exit", 4 * sizeof(char)) == 0;
    else
        return 0;
}


int8_t is_help_case(prun_strc data)
{
    if (data->argc && data->argv != NULL && data->argv[0] != NULL)
        return strncmp(data->argv[0], "help", 4 * sizeof(char)) == 0;
    else
        return 0;
}

